import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from '@angular/router';
import {BehaviorSubject, Observable} from 'rxjs';

@Injectable()
export class SettingRolesService implements Resolve<any> {
    routeParams: any;
    roles: any[];
    onRolesChanged: BehaviorSubject<any>;

    /**
     * Constructor
     *
     * @param {HttpClient} _httpClient
     */
    constructor(
        private _httpClient: HttpClient
    ) {
        // Set the defaults
        this.onRolesChanged = new BehaviorSubject({});
    }

    /**
     * Resolver
     *
     * @param {ActivatedRouteSnapshot} route
     * @param {RouterStateSnapshot} state
     * @returns {Observable<permit> | Promise<permit> | permit}
     */
    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
        this.routeParams = route.params;

        return new Promise((resolve, reject) => {

            Promise.all([
                this.getRoles()
            ]).then(
                () => {
                    resolve();
                },
                reject
            );
        });
    }

    /**
     * Get permissions
     *
     * @returns {Promise<permit>}
     */
    getRoles(): Promise<any> {
        return new Promise((resolve, reject) => {

            this._httpClient.get('http://api.catchadmin.com/roles?page=1&limit=10')
                .subscribe((response: any) => {
                    this.roles = response.data;
                    this.onRolesChanged.next(this.roles);
                    resolve(response);
                }, reject);

        });
    }

    /**
     * Save product
     *
     * @returns {Promise<permit>}
     * @param permit
     */
    saveRole(permit): Promise<any> {
        return new Promise((resolve, reject) => {
            this._httpClient.post('http://127.0.0.1:8000/roles/' + permit.id, permit)
                .subscribe((response: any) => {
                    resolve(response);
                }, reject);
        });
    }

    /**
     * Add product
     *
     * @returns {Promise<permit>}
     * @param permit
     */
    addRole(permit): Promise<any> {
        return new Promise((resolve, reject) => {
            this._httpClient.post('http://127.0.0.1:8000/roles/', permit)
                .subscribe((response: any) => {
                    resolve(response);
                }, reject);
        });
    }

    deleteRole(permit): Promise<any> {
        return new Promise((resolve, reject) => {
            this._httpClient.post('http://127.0.0.1:8000/roles/', permit)
                .subscribe((response: any) => {
                    resolve(response);
                }, reject);
        });
    }
}
